package com.autonavi.abs.generator.core.generator.model;

import com.autonavi.abs.generator.common.enumeration.TemplateEnum;
import com.autonavi.abs.generator.common.model.ColumnMeta;
import com.autonavi.abs.generator.common.model.TableMeta;
import com.autonavi.abs.generator.core.generator.AbstractGenerator;
import com.autonavi.abs.generator.util.GenerateUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author tianquan.ld
 * @version V1.0
 * <p>Description: query 生成器</p>
 * @date 2020-08-10 17:25
 */
@Slf4j
@Component
public class QueryGenerator extends AbstractGenerator {

    private TemplateEnum templateType = TemplateEnum.Query;

    private List<String> fieldList = Lists.newArrayList("limit", "offset", "startTime", "endTime", "deleted"
            , "orderBy", "orderType", "pageIndex", "pageSize");

    @Override
    public TemplateEnum getTemplateTypeEnum() {
        return templateType;
    }

    @Override
    public String getTemplateType() {
        return templateType.name();
    }

    @Override
    public void generate(TableMeta tableMeta) {

        try {

            List<ColumnMeta> columnMetaList = sourceCenterService.getColumnMetaList(tableMeta.getName());
            List<ColumnMeta> filterColumnList = filterField(columnMetaList);

            Map<String, Object> dataMap = Maps.newHashMap();
            dataMap.put("appProperty", app);
            dataMap.put("tableMeta", tableMeta);
            dataMap.put("columnList", filterColumnList);

            GenerateUtil.generateModule(freeMarkerConfigurer, templateType, dataMap);
        } catch (Exception e) {
            log.info("生成失败:{}", templateType.name());
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 过滤BaseDTO已经存在的字段
     *
     * @param columnMetaList
     */
    private List<ColumnMeta> filterField(List<ColumnMeta> columnMetaList) {
        List<ColumnMeta> result = Lists.newArrayList();
        columnMetaList.stream().forEach((column) -> {
            if (fieldList.contains(column.getCamelName())) {
                return;
            }
            result.add(column);

        });
        return result;
    }

}
